# 查询数据库
from django.shortcuts import HttpResponse
from django import forms

from web.models import *

from web.Tools.PublicFn import YYPublicTools_Class

import json

fn = YYPublicTools_Class()
# 商品表
class goods(forms.ModelForm):
    class Meta:
        model = products
        fields = '__all__'


# 根据 id 查询指定商家的导航
def api_select_store_id(request):
    try:
        if request.method == 'POST':
            uid = fn.GetKey(request.POST)['uid']
            row_objs = VendorGoodsNavigator.objects.filter(vendors_id=uid)
            DataList = []
            for obj in row_objs:
                uid = obj.id
                name = obj.name
                update = obj.update_to.strftime('%Y-%m-%d')
                DataList.append({
                    "id": uid,
                    "name": name,
                    "update_to": update
                })
            result = json.dumps(DataList)
            # 根据id查询对应的导航
            return HttpResponse(result, status=200)
    except Exception as e:
        return HttpResponse(f"服务器错误{e}", status=500)

# 获取全部的商家
def api_select_store_all(request):
    if request.method == 'POST':
        vendors_all = vendors.objects.all()
        res_data = []
        for obj in vendors_all:
            uid = obj.id
            name = obj.name
            announcements = obj.announcements
            objdict = {
                "id": uid,
                "name": name,
                "announcements": announcements,
                "store_express": [
                    {"text": obj.score, "icon": "icon-pingfen", "test": "评分", "color": "yy-text-color1"}
                ],

            }
            res_data.append(objdict)
        return HttpResponse(json.dumps(res_data),status=200)
    else:
        return HttpResponse("不支持此请求方式", status=500)

# 根据导航获取该商家导航下的全部商品
def api_select_store_nav_goods_all(request):
    if request.method == 'POST':
        # 商家id
        # 导航id
        vendors_id = request.POST['vendors_id']
        VendorGoodsNavigator_id = request.POST['VendorGoodsNavigator']
        goods_data = products.objects.filter(brand_id=vendors_id, VendorGoodsNavigator_id=VendorGoodsNavigator_id)
        if goods_data:
            # 存储商品数据
            a = []
            for obj in goods_data:
                a.append({
                    "id": obj.id,
                    "name": obj.name,
                    "description": obj.description,
                    "price": obj.price,
                    "stock": obj.stock,
                })
            return HttpResponse(json.dumps(a), status=200)
        else:
            return HttpResponse("[]")
    else:
        return HttpResponse("不支持该请求方式", status=500)